import { getBearerToken, verifyToken } from '../utils/jwt.js'

export function authenticateToken(req, res, next) {
  const token = getBearerToken(req)
  if (!token) return res.status(401).json({ code: 401, data: null, msg: '未提供认证令牌' })
  try {
    const payload = verifyToken(token)
    req.user = { id: payload.sub, username: payload.username }
    next()
  } catch {
    return res.status(401).json({ code: 401, data: null, msg: '令牌无效或已过期' })
  }
}
